package com.hiahiahia.cases.defense.path;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;

@RestController
public class PathCase1 {
    @RequestMapping("/path/case1")
    public void safe_delete(@RequestParam(value="path") String path) {
        String safe_path = safe_path(path);
        File f = new File(safe_path);
        f.delete();      // safe
    }
    public String safe_path(String filePath) {
        /*
         *  防护方法：对用户输入的文件名或者路径名进行过滤，如果存在./,则返回空
         */
        if(!filePath.startsWith("/media/file/") || filePath.contains("./")) {
            return "";
        } else {
            return filePath;
        }
    }
    @RequestMapping("/path/case1_unsafe")
    public void unsafe_delete(@RequestParam(value="path",required = false) String path) {
        File f = new File(path);
        f.delete();     // unsafe
    }

    @RequestMapping("/path/case1_ok")
    public void case1_ok(@RequestParam(value="args")  String[] args) {
        Properties properties = new Properties();
        try {
            FileReader reader = new FileReader("config.properties");
            BufferedReader bufferedReader = new BufferedReader(reader);
            properties.load(bufferedReader);
            bufferedReader.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String appName = properties.getProperty("app.name");
        String appVersion = properties.getProperty("app.version");
        String databaseUrl = properties.getProperty("app.database.url");
        String databaseUsername = properties.getProperty("app.database.username");
        String databasePassword = properties.getProperty("app.database.password");

        System.out.println("App Name: " + appName);
        System.out.println("App Version: " + appVersion);
        System.out.println("Database URL: " + databaseUrl);
        System.out.println("Database Username: " + databaseUsername);
        System.out.println("Database Password: " + databasePassword);
    }
}
